package com.nsoft.html5npub.utils;

import java.util.List;

import com.nsoft.html5npub.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

@SuppressWarnings("deprecation")
public class ChapterViewPanel {
	
	private Context context;
	private ViewGroup parent;
	View popup;
	boolean isVisible = false;

	public ChapterViewPanel(Context c,ViewGroup _parent){
		this.context=c;
		this.parent=_parent;

		popup=((Activity)context).getLayoutInflater().
				inflate(R.layout.pagelist_view,parent,false);

		/**
		popup.setOnClickListener(new 
				View.OnClickListener(){
			
			public void onClick(View v){
				hide();
			}
		});
		*/
	}

	public View getView(){
		return this.popup;
	}

	public void show() {
		int devHeight=utils.getDeviceMetrics(
					this.context).heightPixels;
		
		int quickViewHeight=devHeight/5;
		
		RelativeLayout.LayoutParams lp=
			new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.FILL_PARENT,
				quickViewHeight);
		
		lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

		hide();
		
		parent.addView(popup,lp);
		
		List<Bitmap> bmps=viewengine.getDelegatePages();
		Gallery g=(Gallery)popup.
			findViewById(R.id.previewGallery);
		
		g.setAdapter(new PreviewArrayAdapter(
				this.context,bmps,quickViewHeight));
		
		TextView textTitle=(TextView)popup.findViewById(
				R.id.textPageListName);
		textTitle.setText(R.string.text_chapter_list);
		
		isVisible=true;
	}

	public void hide(){
		if (isVisible){
			isVisible=false;
			((ViewGroup)popup.getParent()).
					removeView(popup);
		}
	}
	
	/**
	 * for adding images to preview gallery
	 * 
	 * @author minhld
	 *
	 */
	private class PreviewArrayAdapter 
				extends ArrayAdapter<Bitmap>{
		private Context context;
		private List<Bitmap> bmpList;
		private int stdHeight;
		
		public PreviewArrayAdapter(Context c,
					List<Bitmap> _bmps,int height) {
			
			super(c,R.layout.preview_image,_bmps);
			this.context=c;
			this.bmpList=_bmps;
			this.stdHeight=height;
		}

		@Override
		public View getView(int position,View convertView,
										ViewGroup parent) {
			LayoutInflater inflater=(LayoutInflater)
					this.context.getSystemService(
						Context.LAYOUT_INFLATER_SERVICE);
			
			View rowView=inflater.inflate(
					R.layout.preview_image,parent,false);
			
			ImageView imageView=(ImageView)rowView.
						findViewById(R.id.previewImage);
			ViewGroup.LayoutParams lp=imageView.getLayoutParams();
			lp.height=this.stdHeight-20;
			lp.width=(int)(lp.height*Constant.pagesize.RATE);
			
			rowView.setLayoutParams(new Gallery.
					LayoutParams(lp.height,lp.height));
			
			imageView.setImageBitmap(bmpList.get(position));
			return rowView;
		}
		
	}
}
